
#include "korners_game_engine_timer.h"

#include <KDebug>


static long lastValue = 0;
static int tid = 0;

KornersGameEngineTimer::KornersGameEngineTimer()
{
    m_value = 0;
    m_started = false;
    m_stop = true;
    lastValue = 0;

    if( ( tid = QObject::startTimer(0) ) == 0 )
	kDebug() << "failed to start game timer";
}

KornersGameEngineTimer::~KornersGameEngineTimer()
{}

void KornersGameEngineTimer::stop()
{
    QObject::killTimer(tid);
}

void KornersGameEngineTimer::startCount()
{
    if( !m_started )
    {
	m_time.start();
	m_started = true;
        m_stop = false;
    }
    else
        m_stop = false;
}

void KornersGameEngineTimer::stopCount()
{
    kDebug() << "stop " << m_value; 
    m_stop = true;
}

QTime KornersGameEngineTimer::value()
{
    return QTime( 0, (m_value/1000)/60, (m_value/1000)%60, m_value%1000 );
}

void KornersGameEngineTimer::startTiming()
{
    kDebug() << "start timing";
    startCount();
}

void KornersGameEngineTimer::makeNextMove( const QPoint& src, const QPoint& dst )
{
    stopCount();
    KornersGameEngineAI::makeNextMove( src, dst );
}

void KornersGameEngineTimer::timerEvent( QTimerEvent* )
{
    if( !m_started )
        return;
    
    if( lastValue == 0 )
        lastValue = m_time.elapsed();
    
    long curValue = m_time.elapsed();
    if( curValue - lastValue > 100 )
    {
        
        if( !m_stop )
        {
            m_value += curValue - lastValue;
            lastValue = curValue;
            emit timeChanged( value() );
        }
        else
            lastValue = curValue;
    }
}
